<template>
  <el-cascader
    v-model="value"
    :options="cityOptions"
    @change="handleCityChange"
    :props="cityProps"
    change-on-select
    clearable
  ></el-cascader>
</template>
<script>
import * as api from '@/api/components'

export default {
  props: {
    value: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      cityOptions: [],
      cityProps: {
        value: 'id',
        label: 'shortName',
        children: 'cities'
      }
    }
  },
  watch: {
    value(newVal, oldVal) {
      // if(newVal.length < oldVal.length ){
      // }
      this.cityOptions.forEach(item => {
        if (
          item.id === newVal[0] &&
          (!item.cities || item.cities.length === 0)
        ) {
          this.getCity([item.id], item.id)
        }
      })
    }
  },
  created() {
    this.getProvince()
  },
  methods: {
    /* 同步val值变化 */
    emitInput(val) {
      this.$emit('input', val)
    },
    /* 省市区改变 */
    handleCityChange(val) {
      /*
       * val为null —— 初始化 获取省列表
       * val.length === 1 [省'0'] —— 点击省，获取市列表
       * val.length === 2 [省'0',市'001']—— 点击市，获取区列表
       */
      this.emitInput(val)
      let id = val[val.length - 1]
      if (val.length === 1) {
        this.getCity(val, id)
      } else if (val.length === 2) {
        this.getArea(val, id)
      }
    },
    /* 获取省 */
    getProvince() {
      api.getProvince().then(response => {
        this.cityOptions = response.data
        // this.getCity(response.data[0].id)
      })
    },
    /* 获取市 */
    getCity(val, id) {
      api.getCity(id).then(response => {
        for (let i = 0; i < this.cityOptions.length; i++) {
          if (this.cityOptions[i].id === val[0]) {
            this.cityOptions[i].cities = response.data
            // this.getArea(response.data[0].id)
            return
          }
        }
      })
    },
    /* 获取区 */
    getArea(val, id) {
      api.getArea(id).then(response => {
        for (let i = 0; i < this.cityOptions.length; i++) {
          if (this.cityOptions[i].id === val[0]) {
            for (let j = 0; j < this.cityOptions[i].cities.length; j++)
              if (this.cityOptions[i].cities[j].id === val[1]) {
                this.cityOptions[i].cities[j].cities = response.data
                return
              }
            return
          }
        }
      })
    }
  }
}
</script>